package models

import (
	db "hulk-api/databases"
	"fmt"
	"strconv"
	"io/ioutil"
	"strings"
	"errors"
)
type SqlList struct {
	Id int 		`json:"id"`
	Createtime string		`json:"createtime"`
	Submitter string		`json:"submitter"`
	Department string		`json:"department"`
	Dbname string		`json:"dbname"`
	Statement string			`json:"statement"`
	Status int				`json:"status"`
	Result string				`json:"result"`
}







type SqlJob struct {
	Id int 						`json:"id"`
	Dbname string				`json:"dbname"`
	Statement string			`json:"statement"`
	SqlPath string 				`json:"sqlpath"`
	Instance string				`json:"instance"`
}



func (job *SqlJob) GetInstance() (  err error ) {
	//var j SqlJob
	row := db.SqlDB.QueryRow("select instance from dbs where name=?" , job.Dbname)
	if err =row.Scan(&job.Instance); err != nil{
		fmt.Printf("scan failed, err:%v",err)
		return
	}
	return
}



//TODO: 如何避免同一个id任务重复执行
func (job SqlJob) DoBySqlpath() ( r string , err error) {
	//var j SqlJob
	fmt.Printf("%+v\n",job)
	//获取job的实例名称
	//需要数据库名不能重复
	job.GetInstance()
	instance := db.Instance(job.Instance)
	conn , err := instance.DbConn(job.Dbname)
	defer conn.Close()
	//获取
	data, err := ioutil.ReadFile(job.SqlPath)
	if err != nil {
		fmt.Println("workflow sqlpath read fatal error: ", err.Error())
		return
	}
	for i,s := range strings.Split(string(data),";") {
		fmt.Println("执行这条SQLLLLLLLLLLLLLLLLLLLLLLLLLLLLLthis current sql is " , s)
		if strings.TrimSpace(s) == "" {
			continue
		}
		result, errr := conn.Exec(s)
		//执行失败
		if errr != nil {
			err = errors.New(fmt.Sprintf("数据任务执行失败 , %s 第%d条SQL，错误：%s ",job.Dbname , i+1,errr.Error()))
			fmt.Println("数据任务执行失败，第N条 ， ", job.Dbname , i)    //执行过程中遇到第一条sql错误即终止
			return
		}
		rowaffected,errr := result.RowsAffected()
		checkErr(errr)
		r = "Query OK, " + strconv.FormatInt(rowaffected,10) + " row affected"

	}
	return


}








//执行查询


//获取慢日志
